const tile = new ol.layer.Tile({
    source: new ol.source.XYZ({
        url: 'http://webrd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8'
    })
})

var map = new ol.Map({
    target: 'map',
    layers: [tile],
    view: new ol.View({
        center: ol.proj.fromLonLat([107.11040599933166, 34.26271532332011]),
        zoom: 4,
        projection: 'EPSG:3857'
    })
});

const url = `https://lzugis.cn/geoserver/lzugis/wms?bbox={bbox}&format=image/png&service=WMS&version=1.1.1&request=GetMap&srs=EPSG:3857&transparent=true&width={width}&height={height}&layers=lzugis:china`
let canvas, ctx;

class WmsRender {
    constructor() {
        canvas = document.createElement('canvas')
        canvas.classList.add('canvas-layer')
        const pNode = map.getViewport()
        pNode.appendChild(canvas)
        const {offsetWidth, offsetHeight} = pNode
        canvas.width = offsetWidth
        canvas.height = offsetHeight
        ctx = canvas.getContext('2d')
        // 设置全局透明度，为了方便与底图做对比
        ctx.globalAlpha = 0.8

        // 注册map事件
        map.on('movestart', () => {
            ctx.clearRect(0,0, canvas.width, canvas.height)
        })
        map.on('moveend', () => {
            this.renderWms()
        })
    }

    renderWms() {
        const bbox = map.getView().calculateExtent()
        const [xmin, ymin, xmax, ymax] = bbox
        const min = map.getPixelFromCoordinate([xmin, ymax])
        const max = map.getPixelFromCoordinate([xmax, ymin])
        const width = Math.floor(max[0] - min[0])
        const height = Math.floor(max[1] - min[1])
        let wmsUrl = url.split('{bbox}').join(bbox.join(','))
        wmsUrl = wmsUrl.split('{width}').join(width)
        wmsUrl = wmsUrl.split('{height}').join(height)
        const image = new Image()
        image.src = wmsUrl
        image.onload = function () {
            ctx.drawImage(image, min[0], min[1])
        }
    }
}

new WmsRender()